import com.xiaoleilu.hutool.util.ReUtil
import java.io.File
import java.nio.charset.Charset
import java.util.ArrayList



/**
 * Created by chenlia on 2017/11/10.
 */
class LuaUtil {
    companion object{

        val requireCode = "require(\"UtilGUI\")\r\n"
        val funcRegex:String = "(function[\u0020a-zA-Z0-9_]+?\\(([\\S]{0,64}?)\\))"
        val charset:String = "UTF8"

        fun proc( str:String ){
            var file = File(str)
            if ( file.isDirectory ) {
                for ( f in file.listFiles() ){
                    LuaUtil.proc(f.absolutePath)
                }
            } else {
                var text = file.readText(Charset.forName(charset))
                text = LuaUtil.addRequire(requireCode,text)
                var funcList =  LuaUtil.getAllFunc(funcRegex,text)
                for ( func in funcList ){
                    var outLog = file.absolutePath +" method="+ LuaUtil.getFuncName(func);
                    text = LuaUtil.addLogOut(func,"    --log.out(\"$outLog\") \r\n",text)
                }
                file.writeText(text)
            }
        }

        fun addLogOut(src:String,src2:String,content:String):String{
            var dst = src + "\r\n" + src2
            return content.replace(src,dst)
        }

        fun getAllFunc(regex: String,content:String):List<String>{
            var result = ReUtil.findAll(regex, content, 1, ArrayList<String>())
            return result;
        }

        fun getFuncName( funcDesc:String ):String{
            return ReUtil.get("function[\u0020]*([\u0020a-zA-Z0-9_]+?)\\(",funcDesc,1)
        }

        fun addRequire(str: String,content:String):String{
            if ( !checkIsRequired(str,content) ){
                return str + "" + content
            } else {
                return content;
            }
        }
        private fun checkIsRequired(str: String,content:String ):Boolean{
            var b = false
            try {
                if ( content.contains(str)){
                    b = true;
                }
            } catch ( e: Exception ){
                e.printStackTrace()
            }
            return b;
        }
    }
}

fun main(args: Array<String>) {
    LuaUtil.proc("C:/Users/chenlia/Desktop/lua/")
//    LuaUtil.proc("C:/Users/chenlia/Desktop/lua/Main.lua")
}
